#pragma once

#include"Log.hpp"
#include<iostream>
#include<memory>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<strings.h>
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include<functional>
#include<vector>
#include<unordered_map>


using namespace std;
using func_t = function<string(const string&, const string&, uint16_t)>;

Log lg;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

string defaultip = "0.0.0.0";
uint64_t defaultport = 8000;
class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const string &ip = defaultip)
    :_port(port)
    ,_ip(ip)
    ,_sockfd(0)
    {}
    
    void Init()
    {
        //打开网卡
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "socket creat error, sockfd : %d", _sockfd);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket creat success, sockfd : %d", _sockfd);

        //bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//需要保证是网络字节序列
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        //bind
        int n = bind(_sockfd, (const sockaddr *)&local, sizeof(local));
        if(n < 0)
        {
            lg(Fatal, "bind error, errno: %d, error string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "Bind success");
    }

    void CheckUser(const struct sockaddr_in &client,const string& clientip,const uint16_t clientport)
    {
        auto iter = _online_user.find(clientip);
        if(iter == _online_user.end())
        {
            _online_user.insert({clientip, client});
            cout<<"["<<clientip<<":"<<clientport<<"] add to online_user"<<endl;
        }
    }

    void BroadCast(const string& info, const string& clientip,const uint16_t clientport)
    {
        for(const auto& user : _online_user)
        {
            string message = "[";
            message += clientip;
            message += ":";
            message += to_string(clientport);
            message += "]#";
            message += info;
            socklen_t len = sizeof(user.second);
            // string echo_string = func(info, clientip, clientport);
            sendto(_sockfd, message.c_str(), message.size(), 0, (const sockaddr*)&user.second, len);
        }
    }

    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[1024];
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&client, &len);
            if(n<0)
            {
                lg(Waring, "recvfrom error, errno: %d, error string: %s", errno, strerror(errno));
                continue;
            }
            uint16_t clientport = ntohs(client.sin_port);
            string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);
            inbuffer[n] = 0;
            string info = inbuffer;
            BroadCast(info, clientip, clientport);
    
        }
    }

    ~UdpServer()
    {
        if(_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;//网络文件描述符
    string _ip;//ip?
    uint16_t _port;//端口号
    bool _isrunning;//是否运行
    unordered_map<string, struct sockaddr_in> _online_user;
};